package com.lst.demo.ui;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.lst.demo.R;

import java.lang.ref.WeakReference;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 静态的Handler + 弱引用 避免内存泄露
 * 其他情况下也可参照此例,静态对象+(Activity)弱引用 来避免内存泄漏
 */
public class TestHandlerActivity extends AppCompatActivity {

    @BindView(R.id.tv_info)
    TextView tvInfo;

    MyHandler mMyHandler;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler);
        ButterKnife.bind(this);
        mMyHandler = new MyHandler(this);
        doInBackground();
    }


    private static class MyHandler extends Handler {
        //弱引用,只要垃圾回收器扫描到该对象,不管内存空间是否够用,都会直接回收掉
        private WeakReference<TestHandlerActivity> mWeakReference;

        public MyHandler(TestHandlerActivity activity) {
            mWeakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //获取弱引用对象
            TestHandlerActivity mainActivity = mWeakReference.get();
            switch (msg.what) {
                case 1:
                    if (mainActivity != null) {
                        mainActivity.doSth(msg.obj + "");
                        mainActivity.doInBackground();
                    }
                    break;
                default:
                    break;
            }
        }
    }

    private void doSth(String msg) {
        tvInfo.setText(msg);
    }

    private void doInBackground() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //模拟耗时操作
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //耗时操作完成，发送消息给UI线程
                Message msg = Message.obtain();
                msg.what = 1;
                msg.obj = "更新UI"+System.currentTimeMillis();
                mMyHandler.sendMessage(msg);
            }
        }).start();

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mMyHandler != null) {
            LogUtils.i("清除handler");
            mMyHandler.removeCallbacksAndMessages(null);
        }

    }


}
